<template>
	<view>
		<!-- 地址 -->
		<navigator url="/pages/address/address?source=1" class="address-section">
			<view class="order-content">
				<text class="yticon icon-shouhuodizhi"></text>
				<view class="cen">
					<view class="top">
						<text class="name">{{addressData.userName}}</text>
						<text class="mobile">{{addressData.userPhone}}</text>
					</view>
					<text class="address">{{addressData.areaName}} {{addressData.userAddress}}</text>
				</view>
				<text class="yticon icon-you"></text>
			</view>

			<image class="a-bg" src=""></image>
		</navigator>

		<view class="goods-section" v-for="(item,index) in carts.carts" :key="item.shopId">
			<view class="g-header b-b">
				<image class="logo" src="https://www.ggshop1688.com/static/images/shop.png"></image>
				<text class="name">{{item.shopName}}</text>
			</view>
			<!-- 商品列表 -->
			<view class="g-item" v-for="(good,ind) in item.list" :key="good.goodsId">
				<image :src="'https://www.ggshop1688.com/' + good.goodsImg"></image>
				<view class="right">
					<text class="title clamp">{{good.goodsName}}</text>
					<text class="spec" v-for="(spec,sind) in good.specNames" :key="spec.itemId">{{spec.catName}}: {{spec.itemName}}</text>
					<view class="price-box">
						<text class="price">￥{{good.shopPrice}}</text>
						<text class="number">x {{good.cartNum}}</text>
					</view>

				</view>
			</view>
			<!-- 优惠明细 -->
			<!-- 			<view class="yt-list">
				<view class="yt-list-cell b-b" @click="toggleMask('show')">
					<view class="cell-icon">
						券
					</view>
					<text class="cell-tit clamp">优惠券</text>
					<text class="cell-tip active">
						选择优惠券
					</text>
					<text class="cell-more wanjia wanjia-gengduo-d"></text>
				</view>
				<view class="yt-list-cell b-b">
					<view class="cell-icon hb">
						减
					</view>
					<text class="cell-tit clamp">商家促销</text>
					<text class="cell-tip disabled">暂无可用优惠</text>
				</view>
			</view> -->
			<!-- 金额明细 -->

			<view class="yt-list">
        <view class="yt-list-cell b-b" @click="showDeliveryMethod(item.shopId)">
          <text class="cell-tit clamp">配送方式</text>
          <view>
            <text class="delivery-text">
              {{ deliveryOptions[shopDelivery[item.shopId]['deliveryType']]['value'] }}
            </text>
            <text class="yticon icon-you"></text>
          </view>
        </view>
				<view class="yt-list-cell b-b">
					<text class="cell-tit clamp">商品金额</text>
					<text class="cell-tip">￥{{item.goodsMoney | moneyFilter}}</text>
				</view>
				<view class="yt-list-cell b-b">
					<text class="cell-tit clamp">优惠金额</text>
					<text class="cell-tip red">-￥{{item.promotionMoney | moneyFilter}}</text>
				</view>
				<view class="yt-list-cell b-b" v-show="pintuanStartId">
					<text class="cell-tit clamp">可用抵扣金</text>
					<text class="cell-tip red">￥{{pintuan_voucher | moneyFilter}}</text>
				</view>
				<view class="yt-list-cell b-b" v-show="pintuanStartId">
					<text class="cell-tit clamp">是否使用拼团抵扣金</text>
					<view class="uni-list">
						<radio-group @change="radioChange">
							<view class="typeBox">
								<view class="font12">
									<radio :value="0+''" style="transform:scale(0.7)" color="#ee5b25" :checked="paychecktype == 0" />不使用
								</view>
								<view class="font12">
									<radio :value="1+''"  style="transform:scale(0.7)"  color="#ee5b25" :checked="paychecktype == 1" />使用
								</view>
							</view>
						</radio-group>
					</view>
				</view>
				<view class="yt-list-cell b-b" v-show="pintuanStartId">
					<text class="cell-tit clamp">是否一直拼团</text>
					<view class="uni-list">
						<radio-group @change="ptstatusChange">
							<view class="typeBox">
								<view class="font12">
									<radio :value="0+''" style="transform:scale(0.7)" color="#ee5b25" :checked="pintuantype == 0" />不使用
								</view>
								<view class="font12">
									<radio :value="1+''"  style="transform:scale(0.7)"  color="#ee5b25" :checked="pintuantype == 1" />使用
								</view>
							</view>
						</radio-group>
					</view>
				</view>
				<view class="yt-list-cell b-b">
					<text class="cell-tit clamp">运费</text>
					<text class="cell-tip">{{shopFreight}}</text>
				</view>
				<view class="yt-list-cell desc-cell">
					<text class="cell-tit clamp">备注</text>
					<input class="desc" type="text" v-model="desc" :placeholder="is_youka?'请输入油卡卡号（必填）':'选填，请输入备注信息'" placeholder-class="placeholder" />
				</view>
			</view>
		</view>



		<!-- 底部 -->
		<view class="footer">
			<view class="price-content">
				<text>实付款</text>
				<text class="price-tip">￥</text>
				<text class="price">{{totalprice | moneyFilter}}</text>
			</view>
			<text class="submit" @click="submit">提交订单</text>
		</view>

		<!-- 优惠券面板 -->
		<view class="mask" :class="maskState===0 ? 'none' : maskState===1 ? 'show' : ''" @click="toggleMask">
			<view class="mask-content" @click.stop.prevent="stopPrevent">
				<!-- 优惠券页面，仿mt -->
				<view class="coupon-item" v-for="(item,index) in couponList" :key="index">
					<view class="con">
						<view class="left">
							<text class="title">{{item.title}}</text>
							<text class="time">有效期至2019-06-30</text>
						</view>
						<view class="right">
							<text class="price">{{item.price}}</text>
							<text>满30可用</text>
						</view>

						<view class="circle l"></view>
						<view class="circle r"></view>
					</view>
					<text class="tips">限新用户使用</text>
				</view>
			</view>
		</view>



    <!--配送类型选择-->
    <uni-popup :mask-click="false" ref="popup" background-color="#fff" type="bottom" @change="change">
      <view class="delivery-type">
        <view class="popup-header">配送方式</view>
        <view class="popup-content">
          <view class="options-delivery">
            <radio-group>
              <view v-for="(options, index) in deliveryOptions"
                    class="yt-list-cell b-b"
                    @click="chooseDelivery(index)"
                    :key="index">
                <text class="cell-tit clamp">{{ options['value'] }}</text>
                <view>
                  <radio :checked="index == deliveryType" :value="options['id'].toString()"/>
                </view>
              </view>
            </radio-group>
          </view>
          <view class="self-mention" v-show="deliveryType == 1 && checkedPoint && checkedPoint.shopId">
            <view @click="$refs.selfPickupPoint.open();" class="ui-list ui-list-text wst-se-store" style="">
              <view class="li-store" style="margin: 0">
                <view class="wst-flex-row wst-jsb wst-ac" style="width:100%;">
                  <view class="wst-flex-column">
                    <view class="wst-flex-row addr-name" style="align-items:baseline;">
                      <span class="infot">{{ checkedPoint.storeName }}</span>
                      <text class="yticon icon-you"></text>
                    </view>
                    <view>
                      <span class="infob">地址：{{ checkedPoint.storeAddress }}</span>
                    </view>
                    <view>
                      <span class="infob">电话：{{ checkedPoint.storeTel }}</span>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <view class="popup-footer ">
          <view class="btn" @click="clearConfiguration">取消</view>
          <view class="btn"  @click="handleDelivery">确认</view>
        </view>
      </view>
    </uni-popup>
    <!--自提店铺-->
    <uni-popup ref="selfPickupPoint" background-color="#fff" type="left" @change="change">
      <view class="choose-popup">
        <view class="popup-header-back">
          <text class="yticon icon-you back" @click="backDelivery">
          </text> 请选择自提点</view>
        <view class="popup-content-options">
          <radio-group v-if="selfPickupPoint.length > 0">
            <view v-for="(point, index) in selfPickupPoint" :key="index" class="li-store" style="margin: 0">
              <view class="wst-flex-row wst-jsb wst-ac" style="width:100%;">
                <view class="wst-flex-column">
                  <view class="wst-flex-row addr-name" @click="choosePickUpPoint(index)" style="align-items:baseline;">
                    <span class="infot">{{ point.storeName }}</span>
                    <radio :checked="index == pointIndex" :value="index.toString()"/>
                  </view>
                  <view>
                    <span class="infob">地址：{{ point.storeAddress }}</span>
                  </view>
                  <view>
                    <span class="infob">电话：{{ point.storeTel }}</span>
                  </view>
                </view>
              </view>
            </view>
          </radio-group>
          <view class="empty-addr" v-else>
            暂无自提地址
          </view>
        </view>
      </view>
    </uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				pintuantype:0,
				pintuan_voucher:0,
				paychecktype:0,
				shopFreight: 0,
				maskState: 0, //优惠券面板显示状态
				desc: '', //备注
				payType: 1, //1微信 2支付宝
				couponList: [{
						title: '新用户专享优惠券',
						price: 5,
					},
					{
						title: '庆五一发一波优惠券',
						price: 10,
					},
					{
						title: '优惠券优惠券优惠券优惠券',
						price: 15,
					}
				],
				addressData: {},
				carts: {},
				payments: [],
				pintuanGoodsId: '',
				pintuanStartId: '',
				totalprice:0,
				is_youka: false,
        goodsId:0,
        seckill_time_id: 0,
        spec_ids:0,

        showDelivery: false,
        shopDelivery:{}, // 店铺配送对象
        deliveryType: 0, // 配送类型数组索引
        pointIndex:0, // 自提点索引
        selfPickupPoint:[], // 自提点
        deliveryOptions: [
          {
            value: '快递运输',
            id: 1,
          },
          {
            value: '自提',
            id: 1,
          }
        ], // 配送类型数组
        deliveryShopId: 0,
        checkedPoint:{},
			}
		},
		onShow() {
			this.initPage();
		},
		onLoad(option) {
      this.goodsId= option.goodsId
      this.seckill_time_id =option.seckill_time_id
      this.spec_ids = option.spec_ids
			//商品数据
			this.pintuanGoodsId = option.pintuanGoodsId;
			this.pintuanStartId = option.pintuanStartId == 'null' ? '0' : option.pintuanStartId;
			console.log('1')
		},
		methods: {

      // 返回配送类型页
      backDelivery(){
        this.$refs.selfPickupPoint.close();
      },

      // 清除配置设置
      clearConfiguration(){
        this.deliveryType = 0;
        this.pointIndex = 0;
        this.selfPickupPoint = [];
        this.deliveryShopId = 0;
        this.$refs.popup.close();
      },

      // 选择配送方式
      async chooseDelivery(index){
        this.deliveryType = index;
        if (index === 1 && this.selfPickupPoint.length <= 0){
          uni.showLoading({
            title: '加载中'
          });

          // 请求
          await this.$Request.request('/api/cart/getStores', 'POST', {
            addressId: this.addressData.addressId,
            shopId: this.deliveryShopId,
          }, true).then(res => {
            if (res.status == 1) {
              const {data:{list}} = res;
              this.selfPickupPoint = list;
              this.shopDelivery[this.deliveryShopId]['selfPickupPoint'] = list;
              // this.$api.msg(res.msg)
            } else {
              this.$api.msg(res.msg)
            }
          }).catch(err => {
            console.log(err)
          }).finally( ()=>{
            // that.$api.msg('暂无自提点')
            uni.hideLoading();
          })
        }
        // console.log('this.selfPickupPoint 2');

        if (this.selfPickupPoint.length <= 0){
          this.deliveryType = 0;
          // setTimeout(()=>{
          //   this.$api.msg('暂无自提点')
          // }, 1111)
          //
          return;
        }
        // console.log('this.pointIndex', this.pointIndex, this.selfPickupPoint, this.selfPickupPoint[this.pointIndex]);

        this.checkedPoint = this.selfPickupPoint[this.pointIndex];
        // console.log(this.checkedPoint);
      },
      // 选择自提点
      choosePickUpPoint(index){
        this.pointIndex = index;
        this.checkedPoint = this.selfPickupPoint[this.pointIndex];
        this.backDelivery();
      },
      // 确认选择
      handleDelivery(){
        this.shopDelivery[this.deliveryShopId].deliveryType = this.deliveryType;
        this.shopDelivery[this.deliveryShopId].point = this.pointIndex;
        this.$refs.popup.close();
        this.clearConfiguration();
      },
      //打开配送方式选择
      showDeliveryMethod(shopId) {
        const {deliveryType, point, selfPickupPoint} = this.shopDelivery[shopId];
        this.deliveryType = deliveryType;
        this.pointIndex = point;
        this.selfPickupPoint = selfPickupPoint;
        this.deliveryShopId = shopId;

        this.$refs.popup.open();
        // 获取自提点
      },
      change(e) {
        console.log('当前模式：' + e.type + ',状态：' + e.show);
      },

      ptstatusChange(e){
				this.pintuantype = e.detail.value;
			},
			radioChange(e) {
				this.paychecktype = e.detail.value;
				if(this.paychecktype != 0){
					if(this.pintuan_voucher > this.totalprice){
						console.log('1')
						this.totalprice = 0;
					}else{
						console.log('2')
						this.totalprice = this.totalprice -  this.pintuan_voucher
					}
				}else{
					this.totalprice =  this.carts.goodsTotalMoney + this.shopFreight
				}
			},
			//显示优惠券面板
			toggleMask(type) {
				let timer = type === 'show' ? 10 : 300;
				let state = type === 'show' ? 1 : 0;
				this.maskState = 2;
				setTimeout(() => {
					this.maskState = state;
				}, timer)
			},
			numberChange(data) {
				this.number = data.number;
			},
			changePayType(type) {
				this.payType = type;
			},
			submit() {
				let shopId = 0;
				let data = {}
				// if(this.addressData)
				if (this.addressData.length == 0) {
					uni.showModal({
						title: '温馨提示',
						content: '您未添加收货地址，请前往添加',
						success: function(res) {
							if (res.confirm) {
								uni.navigateTo({
									url: "../address/address"
								})
							} else if (res.cancel) {

							}
						}
					});
					return;
				}
				if(this.is_youka && !this.desc){
					return this.$api.msg('请填写必填项')
				}
				
				for (let i = 0; i < this.carts.carts.length; i++) {
					shopId = this.carts.carts[i].shopId
					data['deliverType_' + shopId] = 0
					data['storeId_' + shopId] = 0
					data['emark_' + shopId] = ''
					data['couponId_' + shopId] = ''
				}
				if (this.pintuanGoodsId && this.pintuanStartId) {
					data.pintuanGoodsId = this.pintuanGoodsId
					data.pintuanStartId = this.pintuanStartId
				}
				data.desc = this.desc
				data.isInvoice = 0
				data.s_addressId = this.addressData.addressId
				data.s_areaId = this.addressData.area
				data.payType = 4
				data.payCode = 'wallets'
				data.isUseScore = 0
				data.useScore = 5303
				data.pintuanIsUseVoucher = this.paychecktype;
				data.pintuanIsOneKey = this.pintuantype;
				Object.assign(data, {
          goodsId: this.goodsId,
          seckill_time_id: this.seckill_time_id,
          spec_ids: this.spec_ids
        })

        // 判断自提订单
        if (Object.keys(this.shopDelivery).length > 0){
          Object.keys(this.shopDelivery).forEach((index)=>{
            let {id, point, deliveryType, selfPickupPoint} = this.shopDelivery[index];
            data[`deliverType_${id}`] = deliveryType;
            data[`storeId_${id}`] = deliveryType > 0 ? selfPickupPoint[point]['storeId'] : 0;
          })
        }
				let that = this
				that.$Request.request('/api/seckill/submit', 'POST', data, true).then(res => {
					console.log(res)
					if (res.status == 1) {
						that.$api.msg(res.msg)
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/money/pay?pkey=' + res.pkey
							})
						}, 800)

					} else {
						that.$api.msg(res.msg)
					}
				}).catch(err => {
					console.log(err)
				})

				// return
			},
			stopPrevent() {

			},
			async initPage() {
				let that = this
				await that.$Request.request('/api/seckill/settlement', 'GET', {
          goodsId: this.goodsId,
          seckill_time_id: this.seckill_time_id,
          spec_ids: this.spec_ids
        }, true).then(res => {
					if (res.status == 1) {
						console.log(res)
						that.addressData = res.data.userAddress
						this.is_youka = res.data.is_youka
						that.payments = res.data.payments
						that.carts = res.data.carts
						that.shopFreight = res.data.shopFreight
						that.pintuan_voucher = res.data.pintuan_voucher
						that.totalprice = that.carts.goodsTotalMoney + this.shopFreight
            const {carts:{carts}} = res.data;
            let tempShop = {};
            Object.keys(carts).forEach(id=>{
              let item = carts[id];
              tempShop[item.shopId] = {
                id: item.shopId,
                name: item.shopName,
                deliveryType: 0,
                point: 0,
                selfPickupPoint:[],
              }
            });

            console.log(tempShop);
            this.shopDelivery = tempShop;
          }

        }).catch(err => {
					console.log(err)
				})
			}
		}
	}
</script>

<style lang="scss">
.choose-popup{
  height: 100vh;
  .popup-header-back{
    height: 80rpx;
    line-height: 80rpx;
    padding: 0rpx 20rpx;
    text-align: center;
    font-size: 30rpx;
    font-weight: bold;
    background: #f1f0f0;

    .back{
      float: left;
      transform: rotate(180deg);
    }
  }
  .popup-content-options{
    padding: 20rpx;
  }
}
.delivery-text{
  font-size: 26rpx;
  color: #6e6e6e;
}
.delivery-type{
  padding: 20rpx 0rpx;
  .popup-header {
    height: 80rpx;
    line-height: 80rpx;
    padding: 20rpx;
    text-align: center;
    font-size: 30rpx;
    font-weight: bold;
  }
  .popup-content {

    .self-mention {
      padding: 20px;
    }

    padding: 20rpx 0rpx;
  }
  .popup-footer{
    position: relative;
    margin-bottom: 40rpx;

    text-align: center;
    .btn{
      position: relative;

      width: 300rpx;
      display: inline-block;
      min-width: 200rpx;
      color: white;
      height: 80rpx ;
      line-height: 80rpx ;
      &:nth-child(1){
        background: #FFAC2A;
        &:before{
          content: '';
          width: 80rpx;
          height: 80rpx;
          display: block;
          left: -35rpx;
          background: #FFAC2A;
          z-index: 9999;
          position: absolute;
          border-radius: 50% 0% 0% 50%;
          top: 0rpx;
        }
      }
      &:nth-child(2){
        background: #ED413B;
        &:after{
          content: '';
          border-radius: 0% 50% 50% 0% ;
          width: 80rpx;
          height: 80rpx;
          display: block;
          right: -35rpx;
          background: #ED413B;
          z-index: 9999;
          top: 0rpx;
          position: absolute;
        }
      }
    }
  }
}



@import './createOrder.scss';
.ui-list{
  position: relative;
  list-style: none;
  padding: 0px;
  margin: 0px;
  color: #828386;
}

.addr-name{
  display: flex;
  justify-content: space-between;
}
.infot{
  font-size: 30rpx;
  font-weight: bold;
}
.infob{
  font-size: 26rpx;
}
.fr-list{height:28rpx;line-height: 28rpx;background:#fff;border-bottom:1px solid #f2f2f2;}
.ui-icon-push{font-size: 28rpx;}
.wst-se-line{padding:0rpx 10rpx;}
.wst-se-line p{border-bottom:1rpx solid #EDEDED;}
.wst-fr-invoice{padding:0rpx 10rpx;background: #ffffff;font-size:26rpx;}
.wst-fr-invoice textarea{width: 100%;height: 46rpx;padding: 2rpx;}
.wst-fr-invoice textarea:focus{border:1rpx solid #3bb4f2;}
.wst-fr-score{padding-top:15rpx;color:#333;font-size:25rpx;}
.wst-fr-score span{color:#e00102;}

/deep/ .uni-popup__wrapper-box {
  width: 100vw !important;
  border-radius: 0px;
}

.empty-addr{
  text-align: center;
  margin-top: 100rpx;
}

.li-store{
  margin-top: 20rpx!important;
  padding-bottom: 20rpx;
  border-bottom: 1rpx dotted #c7c4c4;
}
</style>

